<template>
  <div ref="carloadBox"
       class="carload-box">
    <div class="right-anchor">
      <Anchors ref="print"
               :span-row="spanRow"
               :nav-list="navList">
        <div v-for="(item, index) in divide"
             :id="`${item.id}`"
             :key="index">
          <div v-if="item.tableData.length">
            <Tables :table-data="item.tableData"
                    :columns="item.columns"
                    :status="bargaStatus"
                    :hidden="hidden"
                    :separate-barga="separateBarga"
                    :label="item.label"
                    :barga-details-status="bargaDetailsStatus"
                    @merge="merge"
                    @bargainEdit="bargainEdit"
                    @bargain="bargain"
                    @edit="edit"
                    @clear="clear" />
          </div>
        </div>
        <el-empty v-if="!empty"
                  description="暂无数据"></el-empty>
      </Anchors>
      <div v-if="valueObject">
        <AddDeliverForm :value="row"
                        :edit-status="editStatus"
                        :unit-header="unitHeader"
                        :status="bargaStatus"
                        :disabled="disabled"
                        @handlerUnit="handlerUnit"
                        @add="addRow" />
      </div>
    </div>
  </div>
</template>

<script>
import AddDeliverForm from './components/AddDeliverForm.vue'
import Anchors from '../transportComponent/components/Anchors.vue'
import Tables from '../transportComponent/tables.vue'
import {
  reduce, addPickData, setArray,
  EditableIncludes,
  addDeliverColumns,
  hasSameTemplateRuleId,
  detailToAddressAssignment,
  isExistingDeliverItem,
  confirmExistingData
} from '../index'
import { mapActions } from "vuex";
import eventBus from "@/libs/eventBus";
// import { v4 } from 'uuid'

export default {
  name: 'Carload',
  components: { AddDeliverForm, Anchors, Tables },
  props: {
    specs: {
      type: Object,
      default: () => { }
    },
    valueObject: {
      type: Boolean,
      default: false
    },
    spanRow: {
      type: [String, Number],
      default: 16
    },
    bargaStatus: {
      type: [String, Number],
      default: null
    },
    response: {
      type: Boolean,
      default: false
    },
    importStatus: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      divide: [],
      navList: [],
      editStatus: null,
      unitValue: null,
      beforeEditStatus: false,
      separateBarga: null,
      bargainIds: null,
      row: {},
      isTip: false,
      areaOptions: [],
      divideRegular: [
        {
          id: 'part1',
          value: 1,
          label: '公斤',
          tableData: [
          ],
          response: false
        },
        {
          id: 'part2',
          value: 2,
          label: '吨',
          tableData: [
          ],
          response: false
        },
        {
          id: 'part3',
          value: 3,
          label: '立方米',
          tableData: [

          ],
          response: false
        },
        {
          id: 'part4',
          value: 4,
          label: '升',
          tableData: [

          ],
          response: false
        },
        {
          id: 'part5',
          value: 5,
          label: '个',
          tableData: [],
          response: false
        },
        {
          id: 'part6',
          value: 6,
          tableData: [],
          label: '托',
          response: false
        },
        {
          id: 'part7',
          value: 7,
          label: '台',
          tableData: [],
          response: false
        },
        {
          id: 'part8',
          value: 8,
          label: '箱',
          tableData: [],
          response: false
        },
        {
          id: 'part9',
          value: 9,
          label: '包',
          tableData: [],
          response: false
        },
        {
          id: 'part10',
          value: 10,
          label: '捆',
          tableData: [],
          response: false
        },
        {
          id: 'part11',
          value: 11,
          label: '辆',
          tableData: [],
          response: false
        },
        {
          id: 'part12',
          value: 12,
          label: '件',
          tableData: [],
          response: false
        },
        {
          id: 'part13',
          value: 13,
          label: '袋',
          tableData: [],
          response: false
        },
        {
          id: 'part14',
          value: 14,
          label: '架',
          tableData: [],
          response: false
        },
        {
          id: 'part15',
          value: 15,
          label: '盒',
          tableData: [],
          response: false
        },
        {
          id: 'part16',
          value: 16,
          label: '桶',
          tableData: [],
          response: false
        },
        {
          id: 'part17',
          value: 17,
          label: '其他',
          tableData: [],
          response: false
        }
      ]
    }
  },
  computed: {
    query () {
      return this.$route.query
    },
    detail () {
      return this.specs?.detailData
    },
    // showDelete () {
    //   return this.detail?.status ? true : false
    // },
    initStatus () {
      return this.query.status || this.query.templateId
    },
    hidden () {
      return this.isShowDelete || !this.query.templateId
    },
    bargaDetailsStatus () {
      return this.query.templateId && Number(this.query.status === 8) ? true : false
    },
    isShowDelete () {
      let haveStatus = null
      // if (this.detail?.status != 11 || this.detail?.status != 14) {
      if (EditableIncludes().includes(this.detail?.status)) {
        haveStatus = true
      } else {
        haveStatus = false
      }
      return haveStatus
    },
    empty () {
      return this.divide?.some(d => d?.tableData?.length > 0)
    },
    delivers () {
      return this.specs?.deliver
    },
    divideTransform () {
      return ({ divide }) => {
        divide.forEach(item => {
          const divideRegularMap = this.divideRegular.map(d => {
            if (item.billingUnit === d.value) {
              this.navList.push({ value: d.value, id: d.id, label: d.label });
              this.navList = setArray(this.navList);
              const rows = addPickData({ item, type: 'to' });
              const columns = addDeliverColumns({ item })
              d.columns = columns
              d.tableData.push(rows);
              // this.separateBarga = d.tableData.some(item => item.bargain)
              if (this.bargainIds || Number(this.query.status) === 8 && this.query.templateId) {
                const bargainList = d.tableData.filter(item => item.bargain)
                if (bargainList) {
                  this.separateBarga = true
                } else {
                  this.separateBarga = false
                }
              }
              for (let i = 0; i < d.tableData.length; i++) {
                if (d.tableData[i].bargain) {
                  const index = i - 1;
                  d.tableData[index].edit = true
                }
              }
              return d
            } else {
              return d
            }
          })
          console.log('divideRegularMap', divideRegularMap)
          this.divide = divideRegularMap
        })
      }
    },
    disabled () {
      const matchingIndex = this.divide.findIndex(item =>
        item.value === this.unitValue && item.tableData.length)
      return matchingIndex !== -1
    },
    unitHeader () {
      const matchingItem = this.divide.find(item =>
        item.value === this.unitValue && item.tableData.length)
      return matchingItem?.tableData[0]?.pricingList || []
    },
    // checkAddressDivides () {
    //   return deliver => {
    //     const delivers = checkToAddressErrors(JSON.parse(JSON.stringify(deliver)), this.areaOptions)
    //     return delivers
    //   }
    // },
    init () {
      return this.divideTransform({ divide: this.delivers })
    }
  },
  watch: {
    'query.templateId': function (vlaue) {
      this.bargainIds = vlaue
    },
    response () {
      this.init
    }
  },
  async created () {
    if (this.initStatus || this.importStatus) {
      this.init
    } else {
      this.divide = this.divideRegular
    }
    // if (this.initStatus) {
    //   // this.divide = this.divideTransform({ divide: this.specs?.divide })
    //   this.divideTransform({ divide: this.specs?.deliver })
    // } else {
    //   this.divide = this.divideRegular
    // }
  },
  mounted () {
    eventBus.$off("clearBargaData");
    eventBus.$on("clearBargaData", () => {
      this.divide.forEach(item => {
        if (item.tableData.length) {
          item.tableData = item.tableData.filter(item => !item.locaBargain)
          item.columns = item.columns.filter(item => item.prop !== 'remarks')
        }
      })
    });
  },
  methods: {
    ...mapActions({
      buffDeliver: "quotation/buffDeliver",
      buffbargaDeliver: "quotation/buffbargaDeliver"
    }),
    handlerUnit ({ value, items }) {
      this.unitValue = value
      this.editStatus = false
    },
    addRow (item) {
      // 添加数据
      const rows = addPickData({ item, type: 'to' })
      // 添加列
      const columns = addDeliverColumns({ item })
      const mergedTableData = []
      const bargaTableData = []
      this.isTip = false
      this.divide = this.divideRegular
      this.divideRegular.forEach(d => {
        if (d.value === rows.billingUnit) {
          // 添加导航栏
          this.navList.push({ value: d?.value, id: d?.id, label: d?.label })
          this.navList = setArray(this.navList)

          /* 已经存在议价上游数据状态 */
          if (this.bargaStatus && this.editStatus && this.bargaStatus !== 3) {
            // 编辑状态
            // d.columns = columns
            // this.editStatus = false
            // d.tableData.splice(item.index + 1, 1, { ...rows, locaBargain: true, edit: false })
            const currentData = d.tableData[item.index]
            const nextData = d.tableData[item.index + 1]

            d.columns = columns
            this.editStatus = false
            if (rows?.templateRuleId === currentData?.templateRuleId && nextData?.locaBargain) {
              d.tableData.splice(item.index + 1, 1, { ...rows, locaBargain: true, edit: false })
            } else {
              d.tableData.splice(item.index + 1, 0, { ...rows, locaBargain: true, edit: false })
            }

          } else if (this.bargaStatus && this.bargainLaterStatus) {
            // 已存在议价下游数据详情
            const transformRows = detailToAddressAssignment({ rows: JSON.parse(JSON.stringify(rows)) })
            d.tableData.splice(item.index, 1, { ...transformRows })
            d.tableData.splice(item.index + 1, 1)
            mergedTableData.push(...d.tableData)

          } else if (this.bargaStatus && this.bargaStatus !== 3) {
            // 议价状态
            // d.columns = columns
            // const tableDataIndex = d.tableData[item.index]
            // const isReduce = reduce({ data: tableDataIndex, rows: rows })
            // if (isReduce) {
            //   d.tableData.splice(item.index + 1, 0, isReduce)
            // }
            const tableDataIndex = d.tableData[item.index]
            const nextData = d.tableData[item.index + 1]
            const isReduce = reduce({ data: tableDataIndex, rows: rows })

            if (isReduce) {
              if (rows?.templateRuleId === tableDataIndex?.templateRuleId && nextData?.locaBargain) {
                d.tableData.splice(item.index + 1, 1, { ...rows, locaBargain: true, edit: false })
              } else {
                d.tableData.splice(item.index + 1, 0, { ...rows, locaBargain: true, edit: false })
              }
            }

          } else if (this.editStatus) {
            // 编辑状态

            this.editStatus = false
            const importedValidation = this.validateRows(rows)
            /* 导入数据编辑 */
            if (!importedValidation) {
              [...Object.keys(rows), ...Object.keys(columns)].forEach(key => {
                if (key.startsWith('is')) {
                  delete rows[key]
                  delete columns[key]
                }
              })
              d.columns = columns
              d.tableData.splice(item.index, 1);
            }
            this.isTip = true
            const transformRows = detailToAddressAssignment({ rows: JSON.parse(JSON.stringify(rows)) })
            const existingItem = isExistingDeliverItem({ tableData: d.tableData, transformRows: transformRows })
            if (existingItem) {
              confirmExistingData().then(res => {
                d.tableData.forEach((item, index) => {
                  if (item.toAddress?.address && transformRows.toAddress?.address
                    && item.toAddress.address === transformRows?.toAddress?.address) {
                    d.tableData.splice(index, 1, { ...transformRows, edit: false })
                  }
                  if (item.toCity === transformRows?.toCity
                    && item.billingUnit === transformRows?.billingUnit
                  ) {
                    d.tableData.splice(index, 1, { ...transformRows, edit: false })
                  }
                })
              })
            } else {
              const index = d.tableData.findIndex(item => item.locaBargain)
              if (index !== -1) {
                d.tableData.splice(index + 1, 0, { ...transformRows, locaBargain: true, edit: false })
              } else {
                d.tableData.unshift({ ...transformRows })
              }
            }
            mergedTableData.push(...d.tableData)

          } else {
            // 添加数据
            const importedValidation = this.validateRows(rows)
            /* 导入数据编辑 */
            if (!importedValidation) {
              [...Object.keys(rows), ...Object.keys(columns)].forEach(key => {
                if (key.startsWith('is')) {
                  delete rows[key]
                  delete columns[key]
                }
              })
              d.columns = columns
              // d.tableData.splice(item.index, 1);
            }
            const transformRows = detailToAddressAssignment({ rows: JSON.parse(JSON.stringify(rows)) })
            // d.tableData.unshift({ ...transformRows })
            d.columns = columns
            if (!d.tableData.length) {
              d.tableData.unshift({ ...transformRows })
              mergedTableData.push(...d.tableData)
              return
            }
            this.isTip = true
            const existingItem = isExistingDeliverItem({ tableData: d.tableData, transformRows: transformRows })
            if (existingItem) {
              confirmExistingData().then(res => {
                console.log('零担重复数据', res)
                d.tableData.forEach((item, index) => {

                  if (item.toCity === transformRows?.toCity
                    && item.billingUnit === transformRows?.billingUnit) {
                    if (item.toAddress.address && item.toAddress.address !== undefined) {
                      if (item.toAddress.address === transformRows?.toAddress?.address) {

                        d.tableData.splice(index, 1, { ...transformRows, edit: false })
                        return
                      }
                      return
                    }
                    d.tableData.splice(index, 1, { ...transformRows, edit: false })
                  }
                })
                // d.tableData.splice(item.index, 1, { ...transformRows, edit: false })
                // d.tableData = this.uniqueArray({ array: d.tableData })
                mergedTableData.push(...d.tableData)
              })
            } else {
              const index = d.tableData.findIndex(item => item.locaBargain)
              if (index !== -1) {
                d.tableData.splice(index + 1, 0, { ...transformRows, locaBargain: true, edit: false })
              } else {
                d.tableData.unshift({ ...transformRows })
              }
            }

          }
        }
        if (d.tableData.length) {
          mergedTableData.push(...d.tableData)
        }
        const bargaData = d.tableData.filter(item => item.locaBargain)
        bargaTableData.push(...bargaData)
      })
      // 设置缓存
      this.buffbargaDeliver({ data: JSON.parse(JSON.stringify(bargaTableData)) })
      this.buffDeliver({ data: JSON.parse(JSON.stringify(mergedTableData)) })
      if (!this.isTip) {
        this.$message.success('操作成功')
      }
    },
    bargain (index, item) {
      const rows = Object.assign({}, item)
      this.selectedArrData = [rows]
      this.unitValue = rows.billingUnit
      if (hasSameTemplateRuleId(this.divide)) {
        // this.row = { row: { ...rows, bargain: true, index: index } }
        this.row = { row: { ...rows, edit: true, index: index, endAddress: rows.toAddress?.address } }
        this.editStatus = true
        return
      }
      this.row = { row: { ...rows, locaBargain: true, index: index, endAddress: rows.toAddress?.address } }
    },
    edit (index, row) {
      if (row?.isToError) {
        row.endCity = []
      }
      const rows = Object.assign({}, row)
      this.selectedArrData = [rows]
      this.unitValue = rows.billingUnit
      this.row = { row: { ...rows, edit: true, index: index, endAddress: row.toAddress?.address } }
      this.editStatus = true
    },

    merge (index, row) {
      let mergedTableData = []
      const rows = Object.assign({}, row)
      rows.bargain = false
      /* 问下产品看是否能再次编辑 */
      rows.edit = true
      this.divide.forEach(item => {
        if (rows.billingUnit === item.value) {
          item.tableData[index - 1] = rows
          item.tableData.splice(index, 1)
        }
        if (item.tableData.length) {
          mergedTableData.push(...item.tableData)
        }
      })
      this.buffDeliver({ data: JSON.parse(JSON.stringify(mergedTableData)) })
    },
    bargainEdit (index, row) {
      const rows = Object.assign({}, row)
      this.selectedArrData = [rows]
      this.unitValue = rows.billingUnit
      this.row = { row: { ...rows, edit: true, index: index } }
      console.log('议价过后', this.row)
      this.bargainLaterStatus = true
      // this.editStatus = true
    },
    clear (index, row) {
      let mergedTableData = []
      let bargaTableData = []
      this.divide.forEach(item => {
        if (row.billingUnit === item.value) {
          item.tableData.splice(index, 1)
          this.clearNavList({ value: item.value })
        }
        if (item.tableData.length) {
          mergedTableData.push(...item.tableData)
        }
        const bargaData = item.tableData.filter(item => item?.locaBargain)
        bargaTableData.push(...bargaData)
      })
      this.buffbargaDeliver({ data: JSON.parse(JSON.stringify(bargaTableData)) })
      this.buffDeliver({ data: JSON.parse(JSON.stringify(mergedTableData)) })
    },
    clearNavList ({ value }) {
      const list = this.navList.filter(item => item.value != value)
      this.navList = list
    },
    // uniqueArray ({ array }) {
    //   return array.filter((item, index, arr) => {
    //     return arr.findIndex(itemInner => (
    //       itemInner.fromCity === item.fromCity
    //       && itemInner.toCity === item.toCity
    //       && itemInner.billingUnit === item.billingUnit
    //       // && itemInner.fromAddress.address === item.fromAddress.address
    //       && itemInner.toAddress.address === item.toAddress.address
    //     )) === index;
    //   })
    // },
    validateRows (rows) {
      const { isToError, isPriceError, isBillingUnitError } = rows;
      return !(isToError || isPriceError || isBillingUnitError)
    }
  }
}
</script>


<style scoped>
.carload-box {
  padding-bottom: 20px;
}
.table-container {
  margin-right: 10px;
  max-height: 400px;
  overflow: auto;
  border: 1px solid var(--prev-color-primary);
}
/*  */
</style>